package com.yitiao.data_algorithms.leetcode.editor.cn;

import com.yitiao.data_algorithms.leetcode.editor.cn.base.ListNode;
import com.yitiao.data_algorithms.leetcode.editor.cn.base.TreeNode;
import com.yitiao.data_algorithms.leetcode.editor.cn.base.Node;

import java.util.LinkedList;
import java.util.Queue;

class PopulatingNextRightPointersInEachNodeIi {
    // 2022-09-16 11:17:04
    public static void main(String[] args) {
        Solution solution = new PopulatingNextRightPointersInEachNodeIi().new Solution();
    }

    //leetcode submit region begin(Prohibit modification and deletion)
/*
// Definition for a Node.*/


    class Solution {

        // 二叉树层序遍历
        public Node connect(Node root) {
            if (root == null) return null;
            Queue<Node> queue = new LinkedList<>();
            queue.offer(root);

            while (!queue.isEmpty()) {
                int n = queue.size();
                Node last = null;
                for (int i = 0; i < n; i++) {
                    Node node = queue.poll();
                    if (i > 0) {
                        last.next = node;
                    }
                    last = node;
                    if (node.left != null) {
                        queue.offer(node.left);
                    }
                    if (node.right != null) {
                        queue.offer(node.right);
                    }
                }
            }
            return root;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}